<?php
namespace app\services\admin;

use app\models\Role;

class RoleService
{
    protected $role;

    public function __construct(Role $role)
    {
        $this->role = $role;
    }

    public function getRole($id)
    {
        $res = $this->role->field('name, slug, status')->where('id', $id)->find();

        if ($res) {
            $result = $res->toArray();
            $result['status'] = $res->getData('status');
            return $result;
        }
        return [];
    }

    public function getRolePermission($id)
    {
        $res = $this->role->where('id', $id)->find();
        $result = [];
        if ($res) {
            $permissions = $res->permissions;
            if ($permissions) {
                foreach ($permissions as $permission) {
                    $result[] = $permission['id'];
                }
            }
        }
        return $result;
    }

    public function getRoleList($status, $search, $size = 15)
    {
        $res = $this->role
            ->withSearch(['name', 'status'], ['name' => $search, 'status' => $status])
            ->order('id', 'desc')
            ->paginate($size);
        if ($res) {
            $pageInfo = $res->toArray();
            /** 由于vue 中要int类型，框架输出的current_page是字符串类型，造成导航页码循环有问题 */
            $pageInfo['current_page'] = intval($pageInfo['current_page']);
            return $pageInfo;
        }

        return [];
    }

    public function getRolesToSelect()
    {
        $res = $this->role->order('id', 'asc')->select();
        $tmp = [];
        if (! $res->isEmpty()) {
            $res->each(function($item) use (& $tmp) {
                $tmp[] = ['id' => $item['id'], 'name' => $item['name']];
            });
        }
        return $tmp;
    }

    public function save($data)
    {
        $res = $this->role
            ->withSearch(['slug'], ['slug' => $data['slug']])
            ->find();

        if ($res) {
            return [false, '已存在标识'];
        }

        if ($this->role->allowField(['name', 'slug', 'status'])->save($data)) {
            return [true, '保存完成'];
        }
        return [false, '未知错误'];
    }

    public function modify($data)
    {
        $res = $this->role->find($data['id']);

        if ($res) {
            $res->name = $data['name'];
            $res->status = $data['status'];

            if ($res->force()->save()) {
                return [true, '保存完成'];
            }
        }
        return [false, '未知错误'];
    }

    public function del($id)
    {
        $res = $this->role->where('id', $id)->delete();

        if ($res) {
            return true;
        }

        return false;
    }

    public function saveAuth($id, $auth)
    {
        $role = $this->role->where('id', $id)->find();
        if ($role) {
            $role->permissions()->where('role_id', $id)->detach();
            if ($auth) {
                return $role->permissions()->save($auth);
            }
            return true;
        }
        return false;
    }
}
